﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace OmniKits.Windows.Converters
{
    public abstract class DuplexConverterBase : TypeConverter, IValueConverter
    {
        public abstract object ConvertAway(object value, Type targetType, CultureInfo culture, ITypeDescriptorContext context, object parameter);
        public abstract object ConvertHere(object value, Type targetType, CultureInfo culture, ITypeDescriptorContext context, object parameter);

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var result = ConvertHere(value, null, culture, context, null);
            if (result == DependencyProperty.UnsetValue)
                throw new NotSupportedException();
            return result;
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            var result = ConvertAway(value, destinationType, culture, context, null);
            if (result == DependencyProperty.UnsetValue)
                throw new NotSupportedException();
            return result;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                return ConvertAway(value, targetType, culture, null, parameter);
            }
            catch
            {
                return DependencyProperty.UnsetValue;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                return ConvertHere(value, targetType, culture, null, parameter);
            }
            catch
            {
                return DependencyProperty.UnsetValue;
            }
        }
    }
}
